/*
 * The Private Message Data Access Object, it handles all database transactions between the front end and the database.
 */

package airport.forum.dao;

//import java.util.Date;
//import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
//import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

//import airport.forum.pojo.Forum;
import airport.forum.pojo.PrivateMessage;
//import airport.forum.pojo.Thread;


//adds a private message to the database
@SuppressWarnings("deprecation")
public class PrivateMessageDAO {
	private static SessionFactory factory = new AnnotationConfiguration()
			.configure().addAnnotatedClass(PrivateMessage.class)
			.addPackage("com.xyz").buildSessionFactory();

	public void addPrivateMessage(PrivateMessage pm) {
		try {
			Session session = factory.openSession();
			Transaction tx = null;
			try {
				tx = session.beginTransaction();
				session.save(pm);
				tx.commit();
			} catch (HibernateException e) {
				if (tx != null)
					tx.rollback();
				e.printStackTrace();
			} finally {
				session.close();
			}
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	//gets the number of unread messages a user has for display on their profile page
	@SuppressWarnings({ "unchecked", "unused" })
	public int getUnreadMessagesCount(String receiver) {
		int msgCount = 0;
		try {
			Session session = factory.openSession();
			Transaction tx = null;
			try {
				String hql = "FROM PrivateMessage P WHERE P.read = 'false' AND P.receiver = '"
						+ receiver + "'";
				// System.out.println(hql);
				Query query = session.createQuery(hql);
				List<String> results = query.list();

				msgCount = results.size();
			} catch (HibernateException e) {
				if (tx != null)
					tx.rollback();
				e.printStackTrace();
			} finally {
				session.close();
			}
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}

		return msgCount;
	}

	// gets a list of PMs in the inbox of the user that received them
	@SuppressWarnings({ "unchecked", "unused" })
	public List<PrivateMessage> getMessageList(String receiver) {
		List<PrivateMessage> pmList = new LinkedList<PrivateMessage>();
		try {
			Session session = factory.openSession();
			Transaction tx = null;
			try {
				String hql = "FROM PrivateMessage P WHERE P.receiver = '"
						+ receiver + "' ORDER BY P.messageId DESC";
				// System.out.println(hql);
				Query query = session.createQuery(hql);
				List<PrivateMessage> results = query.list();
				pmList = results;
			} catch (HibernateException e) {
				if (tx != null)
					tx.rollback();
				e.printStackTrace();
			} finally {
				session.close();
			}
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}
		return pmList;
	}
	
	
	//gets total number of messages a given user has
	@SuppressWarnings({ "unchecked", "unused" })
	public int getTotalMessagesCount(String receiver) {
		int msgCount = 0;
		try {
			Session session = factory.openSession();
			Transaction tx = null;
			try {
				String hql = "FROM PrivateMessage P WHERE P.receiver = '"
						+ receiver + "'";
				// System.out.println(hql);
				Query query = session.createQuery(hql);
				List<String> results = query.list();

				msgCount = results.size();
			} catch (HibernateException e) {
				if (tx != null)
					tx.rollback();
				e.printStackTrace();
			} finally {
				session.close();
			}
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}

		return msgCount;
	}

	//retrieves a PM with the given id
	@SuppressWarnings({ "unchecked", "unused" })
	public PrivateMessage getPm(int pmId) {
		PrivateMessage pm = new PrivateMessage();
		System.out.println("Entering DAO -- get Private Message by ID");
		try {
			Session session = factory.openSession();
			Transaction tx = null;
			try {
				System.out.println("GET PM DAO!!!!--BY ID");
				String hql = "FROM PrivateMessage P WHERE P.messageId = '"
						+ pmId + "'";
				System.out.println("GET PM DAO!!!!--BY ID 1");
				System.out.println(hql);
				Query query = session.createQuery(hql);
				System.out.println("GET PM DAO!!!!--BY ID 2");
				List<PrivateMessage> results = query.list();
				System.out.println("GET PM DAO!!!!--BY ID 3");
				pm = results.get(0);
				System.out.println("GET PM DAO!!!!--BY ID 4");
			} catch (HibernateException e) {
				if (tx != null)
					tx.rollback();
				e.printStackTrace();
			} finally {
				session.close();
			}
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}
		return pm;
	}

	// sets boolean "messageRead" to true when a user first accesses a private
	// message
	public void setMessageToRead(int pmId) {
		try {
			Session session = factory.openSession();
			Transaction tx = null;
			try {
				 tx = session.beginTransaction();
				String hql = "UPDATE PrivateMessage set read = '1' WHERE messageId = '" +pmId+"'";
				        	 Query query = session.createQuery(hql);
				        	 int result = query.executeUpdate();
				        	 tx.commit();
				        	 System.out.println("Rows affected: " + result);
				
			} catch (HibernateException e) {
				if (tx != null)
					tx.rollback();
				e.printStackTrace();
			} finally {
				session.close();
			}
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
	
	//deletes the given PM from the database	
	public void deletePm(int pmId) {
		try {
			Session session = factory.openSession();
			Transaction tx = null;
			try {
				 tx = session.beginTransaction();
				 String hql = "DELETE FROM PrivateMessage WHERE messageId = "  + pmId;
				 Query query = session.createQuery(hql);
	        	 int result = query.executeUpdate();
	        	 tx.commit();
	        	 System.out.println("Rows affected: " + result);
	        	 
			} catch (HibernateException e) {
				if (tx != null)
					tx.rollback();
				e.printStackTrace();
			} finally {
				session.close();
			}
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
}
